﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Resources;
using System.IO.IsolatedStorage;

namespace Pauliom.Theming
{
    public class ThemeResourceDictionary : ResourceDictionary
    {

        public ThemeResourceDictionary()
        {
            //MergeThemeResources();    
        }
        
        public static bool IsDarkTheme()
        {
            Visibility v = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];

            if (v == System.Windows.Visibility.Visible)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        string _kind;
        public string Kind
        {
            get { return _kind; }
            set
            {
                if (_kind != value)
                {
                    _kind = value;

                    try
                    {
                        switch (_kind.ToLower())
                        {
                            case "theme":
                                {
                                    MergeThemeResources();

                                }
                                break;
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e.Message);
                    }
                }
            }
        }


        private void MergeThemeResources()
        {
            string theme = "Light";
            if (IsDarkTheme())
            {
                theme = "Dark";
            }


            ResourceDictionary res = LoadXaml<ResourceDictionary>(new Uri(string.Format(Application.Current.ToString().Replace(".App", "") +
                ";component/Themes/{0}.xaml",
                theme), UriKind.RelativeOrAbsolute));

            MergedDictionaries.Add(res);
        }

        T LoadXaml<T>(Uri uri)
        {
            StreamResourceInfo info = Application.GetResourceStream(uri);
            if (info != null)
            {
                using (StreamReader reader = new StreamReader(info.Stream))
                {
                    return (T)XamlReader.Load(reader.ReadToEnd());
                }
            }

            return default(T);
        }
    }
}
